from common.response import Response
from models import Book, db
from util.jsonUtil import book2dict, dict2book
from common.response import response2dict


def getAllBookList():
    books = Book.query.all()
    code = "200"
    msg = "查询成功"
    data = [book2dict(book) for book in books]
    response = Response(code, msg, data)
    return response2dict(response)


def getOneBook(bookId):
    book = Book.query.filter_by(id=bookId).first()
    code = "200"
    msg="查询成功"
    deta=book2dict(book)
    response = Response(code, msg, deta)
    return response2dict(response)


def getBookByNmae(name):
    books = Book.query.all()
    books0 = []
    print(name)
    for book in books:
        if name in book.name:
            books0.append(book)
    code = "200"
    msg = "查询成功"
    data = [book2dict(book) for book in books0]
    response = Response(code, msg, data)
    return response2dict(response)


def addBook(book):
    book0 = Book.query.order_by(Book.id.desc()).first()
    print(book0)
    book.id = book0.id + 1
    db.session.add(book)
    db.session.commit()
    code = "200"
    msg = "添加成功"
    deta = book2dict(book)
    response = Response(code, msg, deta)
    return response2dict(response)


def updateBook(bookId, book0):
    book = Book.query.get(bookId)
    book.name = book0.name
    book.author = book0.author
    book.introduction = book0.introduction
    book.code = book0.code
    book.picture = book0.picture
    book.price = book0.price
    book.location = book0.location
    book.num = book0.num
    book.sort = book0.sort
    book.score = book0.score
    db.session.commit()
    code = "200"
    msg = "更新成功"
    deta = book2dict(book)
    response = Response(code, msg, deta)
    return response2dict(response)


def deleteBook(bookId):
    book = Book.query.get(bookId)
    db.session.delete(book)
    db.session.commit()
    code = "200"
    msg = "删除成功"
    deta = book2dict(book)
    response = Response(code, msg, deta)
    return response2dict(response)

